# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class ZhihuSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class ZhihuDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        cookie = "edu_user_uuid=edu-v1|69934b07-b719-40da-bfd4-852ca4e2e1da; _xsrf=jQTiuwAx6XdQiTMI3lPoIxCTVVp7ATDX; BEC=e9bdbc10d489caddf435785a710b7029; EDU_TRACE_ID=74a33b95-baf2-4204-97fd-2e97d8614937; _zap=8c537446-e5e3-4d6d-8b3d-6b2afc9d8506; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1733400375; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1733400375; HMACCOUNT=4655DB3D14BEE177; d_c0=ACBSRVfBpRmPToDhEOM0LsdH2Q7YzU57cdM=|1733400375; captcha_session_v2=2|1:0|10:1733400375|18:captcha_session_v2|88:eXVPSGJaTE1mUnNGbUMvM3U3dmJ6aHpCUC82VTdWbmYzWGIwZUtBRUNjZ2djaXBPMUFERzg5ZEc4SVJLQnU2Uw==|15bfbb92b8a710dc533a74f9b48fd563a6e6b825e7e9b248235f9a4600c0dd34; z_c0=2|1:0|10:1733400401|4:z_c0|92:Mi4xR3ZsQUNBQUFBQUFBSUZKRlY4R2xHU1lBQUFCZ0FsVk5VZVUtYUFCOFVBT1BpSVlTcUFlTmNidEFqVEpSanJ0TjBR|fd3e8cdbe94fd01d8fc4a67d6ce52f885aa68099e79d22f06f34d6ce90dab7b9; EDU_MEMBER_HASH_ID=d9e0d66a1112050d4c70a00890e5bb83"
        user_agents = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:92.0) Gecko/20100101 Chrome/92.0.4515.159 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
        ]


        request.headers["Referer"] = "https://www.zhihu.com/"
        request.headers["sec-ch-ua-mobile"] = "?0"
        request.headers["sec-ch-ua-platform"] = '"macOS"'
        request.headers["sec-ch-ua"] = '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"'
        request.headers["sec-fetch-dest"] = "empty"
        request.headers["sec-fetch-mode"] = "cors"
        request.headers["sec-fetch-site"] = "same-site"
        request.headers["User-Agent"] = user_agents[3]

        request.headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)
